package com.base.http

import android.os.Handler
import android.os.Looper
import java.security.MessageDigest

/**
 * 请求md5加密协议
 */
object MD5Signature {
    const val SIGNATURE = ""

    /**
     * 根据Key Value签名
     */
    fun signature(map: Map<String,String>,url: String = ""): String {
        var list = arrayListOf<String>()
        for((key,value) in map){
            list.add("\"$key\":\"$value\"")
        }
        return signature(list,url)
    }

    fun signature(list: List<String>,url: String = ""): String{
        val list = list.sorted()
        val builder = StringBuilder()
        builder.append("[")
        for (i in list.indices){
            builder.append("${list[i].trim()}")
            if(i+1 != list.size){
                builder.append(",")
            }
        }
        builder.append("]")
        return signature("${builder}${SIGNATURE}",url)
    }

    private fun signature(str: String ,url: String = ""): String{
        val messageDigest: MessageDigest

        try {
            messageDigest = MessageDigest.getInstance("MD5")
            messageDigest.reset()
            messageDigest.update(str.toByteArray(charset("UTF-8")))
            val byteArray = messageDigest.digest()
            val md5StrBuff = StringBuffer()
            for (i in byteArray.indices) {
                if (Integer.toHexString(0xFF and byteArray[i].toInt()).length == 1) md5StrBuff.append(
                    "0"
                ).append(Integer.toHexString(0xFF and byteArray[i].toInt())) else md5StrBuff.append(
                    Integer.toHexString(0xFF and byteArray[i].toInt())
                )
            }
            // 16位加密，从第9位到25位
            // String md5Str = md5StrBuff.substring(8, 24).toUpperCase();
            // 32位加密
//            val md5 = md5StrBuff.toString().replace("a".toRegex(), "c").replace("b".toRegex(), "d")
            val md5 = md5StrBuff.toString().toLowerCase()
            Handler(Looper.getMainLooper()).post{
//                Log.i("TAG", ">>>  url =${url}  data = $str   mod5 = $md5 token = ${token}")
            }
            return md5
        } catch (e: Exception) {}
        return ""
    }
}